from django.shortcuts import render
from django import http
from django.views import View
import json
from apps.orders.models import Order
from aijia_project.utils.views import LoginRequiredJSONMixin


# Create your views here.

class TakeOrderView(View):
    """接收订单拒绝订单"""

    def put(self, request, order_id):
        """
        /api/v1.0/orders/[int:order_id]/status
        """

        # 获取参数（接单、拒单）
        action = request.GET.get('action')
        reason = request.GET.get('reason')  # 拒绝订单时传递的数据需要添加到数据库中

        # 检验参数
        if action not in ('accept', 'reject'):
            return http.JsonResponse({"errno": "4103", "errmsg": "参数错误"})

        # 实现核心逻辑
        # 根据订单号查询该订单（要求待接单状态)
        try:
            orders = Order.objects.filter(id=order_id, status=Order.ORDER_STATUS["WAIT_ACCEPT"])

            # 获取房东id
            house = orders.house
        except Exception:
            return http.JsonResponse({"errno": "4001", "errmsg": "获取数据失败"})

        # 判断orders为None
        if not orders:
            return http.JsonResponse({"errno": "400", "errmsg": "获取数据失败"})

        # 判断用户是否是该房子的房东
        user_id = request.user.id
        if not house.user != user_id:
            return http.JsonResponse({"errno": "400", "errmsg": "操作失败"})

        if action == 'accept':
            # 如果是接单将订单状态改为待支付
            orders.status = Order.ORDER_STATUS["WAIT_COMMENT"]
            orders.save()

        elif action == 'reject':
            # 如果是拒单获取拒单原因将订单状态改为已拒绝
            orders.status = Order.ORDER_STATUS["REJECTED"]
            if reason == None:
                return http.JsonResponse({"errno": "400", "errmsg": "操作失败"})

            orders.comment = reason
            orders.save()

        # 响应结果
        return http.JsonResponse({"errno": "0", "errmsg": "操作成功"})


class EvaluateOrderView(View):
    """评价订单"""

    def put(self, request, order_id):
        """/api/v1.0/orders/[int:order_id]/comment"""
        # 获取参数
        comment = request.GET.get('comment')

        # 校验参数
        if not comment != None:
            return http.JsonResponse({"errno": "4103", "errmsg": "参数校验失败"})

        # 实现核心逻辑
        # 根据订单号查询该订单（要求待评价状态只能评论自己下单的订单)
        user_id = request.user.id
        try:
            orders = Order.objects.filter(id=order_id, user_id=user_id, status=Order.ORDER_STATUS["WAIT_COMMENT"])

        except Exception:
            return http.JsonResponse({"errno": "400", "errmsg": "获取数据失败"})

        # 判断orders为None
        if not orders:
            return http.JsonResponse({"errno": "400", "errmsg": "获取数据失败"})

        # 状态改为已完成
        orders.status = Order.ORDER_STATUS["COMPLETE"]
        orders.save()

        # 响应结果
        return http.JsonResponse({"errno": "0", "errmsg": "操作成功"})
